package com.wxy.ideaplugin.generator;

import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;

import java.io.File;
import java.util.List;
import java.util.Set;

/**
 * Created by wxy on 2020/5/22.
 */
public class MpFileWriter {
    private List<FileOutConfig> focList;
    private Set<String> outPathList;

    public MpFileWriter(List<FileOutConfig> focList, Set<String> outPathList) {
        this.focList = focList;
        this.outPathList = outPathList;
    }

    public void write(String templatePath, String outputDir, String suffixPath) {
        write(templatePath, outputDir, false, suffixPath);
    }

    public void write(String templatePath, final String outputDir, boolean hasEntityPath, String suffixPath) {
        write(templatePath, outputDir, hasEntityPath, suffixPath, null);
    }

    public void write(String templatePath, final String outputDir, boolean hasEntityPath, String suffixPath, String appendPath) {
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // vue中最后一个目录是entityName
                String outputDirTmp = outputDir;
                if (hasEntityPath) {
                    outputDirTmp = outputDir + File.separator + tableInfo.getEntityPath();
                }
                // java中类名和entityName有关
                String targetFile = suffixPath;
                if (suffixPath.contains("%s")) {
                    targetFile = tableInfo.getEntityName()+suffixPath.substring(suffixPath.indexOf("%s")+2);
                }
                String path = getGeneratorViewPath(outputDirTmp, targetFile);
                outPathList.add(path);
                return path;
            }
        });
    }



    /**
     * 页面生成的文件名
     */
    public static String getGeneratorViewPath(String outputDir, String suffixPath) {
        if (!new File(outputDir).exists()) {
            new File(outputDir).mkdirs();
        }
        String path = outputDir + "/" + suffixPath;
        File viewDir = new File(path).getParentFile();
        if (!viewDir.exists()) {
            viewDir.mkdirs();
        }
        return path;
    }

}
